//
//  PostDetailViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/12/10.
//  Copyright © 2020 王洋. All rights reserved.
//
#import "CommonPostModel.h"

#import "PostDetailHeaderView.h"
#import "PostDetailImageCell.h"
#import "PostDetailTextCell.h"

#import "CommonEvaluateCell.h"
#import "CommonEvaluateHeaderView.h"
#import "CommonEvaluateFoldFooterView.h"

#import "QADetailSectionHeaderView.h"
#import "CommonNoEvaView.h"

#import "ReportReasonViewController.h"
#import "ReportReasonViewController.h"
#import "PostListViewController.h"
#import "CommonEvaluateBottomView.h"
#import "PostDetailViewController.h"

@interface PostDetailViewController ()<UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableview;

@property (nonatomic, strong) CommonEvaluateBottomView *bottomView;

@property (nonatomic, strong) UIButton *actionBtn;

@property (nonatomic, strong) CommonPostModel *model;

@property (nonatomic, strong) NSMutableArray <CommunityEvaModel *>*dataArray;


@property (nonatomic, strong) dispatch_group_t group;

@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, assign) NSInteger pageNum;

@property (nonatomic, assign) NSInteger total;

//用于记录上拉之前的pagenum
@property (nonatomic, assign) NSInteger latestPageNum;

//对方的模型
@property (nonatomic, strong) CommunityEvaModel *aimModel;

@end

@implementation PostDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initView];
    [self refreshParam];
    [self request_data];
}

- (void)refreshParam {
    self.pageSize = 10;
    self.pageNum = 1;
    self.latestPageNum = self.pageNum;
}

- (void)initView {
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setTitleColor:UIColorHex(0x666666) forState:UIControlStateNormal];

    [rightBtn setImage:[UIImage imageNamed:@"more_icon"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(moreAction) forControlEvents:UIControlEventTouchUpInside];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    rightBtn.frame = CGRectMake(0,0,40,30);
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItems =@[rightItem];
    
    self.actionBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.actionBtn.backgroundColor = UIColor.whiteColor;
    self.actionBtn.titleLabel.font= [UIFont systemFontOfSize:18];
    [self.actionBtn setTitleColor:UIColorHex(0x222222) forState:UIControlStateNormal];
    [self.actionBtn addTarget:self action:@selector(goList) forControlEvents:UIControlEventTouchUpInside];

    [self.actionBtn setImage:[UIImage imageNamed:@"navi_arrow_right"] forState:UIControlStateNormal];
    self.navigationItem.titleView = self.actionBtn;
    
    [self initViewAction];
}

- (void)goList {
    
    PostListViewController *vc = [[PostListViewController alloc] init];
    vc.tid = self.model.themeId;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)initViewAction {
    
    WEAKSELF
    self.bottomView.CommonEvaluateBottomViewBlock = ^(CommunityActionType type) {
      
        switch (type) {
            case CommunityActionType_Eva:{
                weakSelf.bottomView.contentTF.placeholder = @"说说您的见解...";
                weakSelf.bottomView.contentTF.tag = DetailreplyType_post;
                [weakSelf.bottomView.contentTF becomeFirstResponder];
            } break;
            case CommunityActionType_Thumb:{
                [weakSelf request_postThumbWithType:DetailreplyType_post WithModel:weakSelf.model];
            } break;
            case CommunityActionType_Share:{
                [weakSelf share];
            } break;
            default:
                break;
        }
        
    };
}

#pragma mark Share
- (void)share {
    CommonShareModel *model = [[CommonShareModel alloc] init];
    model.url = [NSString stringWithFormat:@"%@%@?pid=%@&replyUserId=%@&myCode=%@",BA_GlobalH5_Domain,@"/postDetailShare",self.pid,[TTUserModel sharedObject].userId,[TTUserModel sharedObject].myCode];
    model.title = self.model.title;
    model.content = self.model.content;
    model.image = [UIImage imageNamed:@"ba_logo"];
    [[TT_ShareManager share] callShareViewWithModel:model];
}

- (void)request_data {
    
    [SVProgressHUD showWithStatus:@"正在请求数据"];
    self.group = dispatch_group_create();

    dispatch_group_enter(self.group);
    dispatch_group_async(self.group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self request_postDetail];
    });
    
    dispatch_group_enter(self.group);
    dispatch_group_async(self.group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self request_evaList];
    });

    dispatch_group_notify(self.group, dispatch_get_main_queue(), ^{
        
        [SVProgressHUD dismiss];
        [self.tableview.mj_header endRefreshing];
        [self.tableview.mj_footer endRefreshing];
        
        [self.bottomView fillWithModel:self.model];
        [self.tableview reloadData];

    });
}

- (void)moreAction {
    
    WEAKSELF
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *liveAction = [UIAlertAction actionWithTitle:@"举报"
                                             style:UIAlertActionStyleDefault
                                           handler:^(UIAlertAction *action) {
        ReportReasonViewController *vc = [[ReportReasonViewController alloc] init];
        vc.baseId = self.model.pid;
        vc.level = @"1";
        vc.type = BAReportType_post;
        [weakSelf.navigationController pushViewController:vc animated:YES];
        
    }];
    UIAlertAction *blockAction = [UIAlertAction actionWithTitle:@"拉黑"
                                             style:UIAlertActionStyleDefault
                                           handler:^(UIAlertAction *action) {
        [weakSelf blockAction];
    }];
    
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消"
                                           style:UIAlertActionStyleCancel
                                         handler:^(UIAlertAction *action) {

    }];

    [alertController addAction:blockAction];
    [alertController addAction:liveAction];
    [alertController addAction:cancleAction];
    [alertController setModalPresentationStyle:UIModalPresentationPopover];
    [self presentViewController:alertController animated:YES completion:nil];
}
- (void)blockAction {
    WEAKSELF
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"确定拉黑该用户？" message:@"拉黑后此用户不能关注您, 也无法给您发送任何消息。并减少此用户话题分享等信息。" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureleAction = [UIAlertAction actionWithTitle:@"确认"
                                           style:UIAlertActionStyleDefault
                                         handler:^(UIAlertAction *action) {
        [SVProgressHUD showWithStatus:@"拉黑成功~"];
        [SVProgressHUD dismissWithDelay:1];
        [self.navigationController popViewControllerAnimated:YES];
    }];
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消"
                                           style:UIAlertActionStyleCancel
                                         handler:^(UIAlertAction *action) {

    }];
    [alertController addAction:cancleAction];
    [alertController addAction:sureleAction];
    [alertController setModalPresentationStyle:UIModalPresentationPopover];
    [self presentViewController:alertController animated:YES completion:nil];
}
- (void)callSectionTFWithIndex:(NSInteger)index {
    
    self.bottomView.contentTF.tag = DetailreplyType_user;
    self.aimModel = self.dataArray[index];
    [self.bottomView.contentTF becomeFirstResponder];
    self.bottomView.contentTF.placeholder = [NSString stringWithFormat:@"回复:%@",self.dataArray[index].userNickName];
}

- (void)callCellTFWithIndexPath:(NSIndexPath *)indexPath {
    
    self.bottomView.contentTF.tag = DetailreplyType_replayUser;
    
    CommunityEvaModel *cellModel = self.dataArray[indexPath.section - PostDetailSectionType_moreEva].sysPostChildSideList[indexPath.row];
    self.aimModel = cellModel;
    [self.bottomView.contentTF becomeFirstResponder];
    self.bottomView.contentTF.placeholder = [NSString stringWithFormat:@"回复:%@",cellModel.replyUserNickName];
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    
    //判断后将tag变回原来的样子
    self.bottomView.contentTF.placeholder = @"说说您的见解...";
    self.bottomView.contentTF.tag = DetailreplyType_post;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    switch (textField.tag) {
        case DetailreplyType_post:{
            [self request_postEvaWithType:DetailreplyType_post];
        } break;
        case DetailreplyType_user:{
            [self request_postEvaWithType:DetailreplyType_user];
        } break;
        case DetailreplyType_replayUser:{
            [self request_postEvaWithType:DetailreplyType_replayUser];
        } break;
        default:
            break;
    }
    
    //判断后将tag变回原来的样子
    self.bottomView.contentTF.placeholder = @"说说您的见解...";
    self.bottomView.contentTF.tag = DetailreplyType_post;

    return YES;
}

#pragma mark UITableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2 + self.dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    switch (section) {
        case PostDetailSectionType_imgText:{
            return 1 + self.model.sysMediaList.count;
        } break;
        case PostDetailSectionType_evaTap:{
            return 0;
        } break;
        default:{
            
            CommunityEvaModel *model = self.dataArray[section - PostDetailSectionType_moreEva];
            if (model.isFold) {
                
                if (model.sysPostChildSideList.count > 1) {
                    return 1;
                } else {
                    return model.sysPostChildSideList.count;
                }
            } else {
                return model.sysPostChildSideList.count;
            }
            
        } break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    switch (section) {
        case PostDetailSectionType_imgText:{
            return 65 + [Utilities getStringHeightWithText:self.model.title font:[UIFont boldSystemFontOfSize:20] viewWidth:(TTScreenWidth - 28)];
        } break;
        case PostDetailSectionType_evaTap:{
            return 50;
        } break;
        default:{
//            return 80;
            return [CommonEvaluateHeaderView calculateHeightWithModel:self.dataArray[section - PostDetailSectionType_moreEva]];

        } break;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.section) {
        case PostDetailSectionType_imgText:{
            
            if (indexPath.row == 0) {
                return self.model.textHeight;
            } else {
                return self.model.sysMediaList[indexPath.row-1].itemHeight;
            }

        } break;
        case PostDetailSectionType_evaTap:{
            return CGFLOAT_MIN;
        } break;
        default:{
            
            CommunityEvaModel *model = self.dataArray[indexPath.section - PostDetailSectionType_moreEva].sysPostChildSideList[indexPath.row];
            CGFloat height = [CommonEvaluateCell calculateHeightWithModel:model];
            return height;
        } break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    switch (section) {
        case PostDetailSectionType_imgText:{
            return 20;
        } break;
        case PostDetailSectionType_evaTap:{
            
            if (self.dataArray.count == 0) {
                return 300;
            } else {
                return CGFLOAT_MIN;
            }
        } break;
        default:{
            
            if (self.dataArray[section - PostDetailSectionType_moreEva].sysPostChildSideList.count > 1) {
                return 30;
            } else {
                return 10;
            }            
        } break;
    }
    return CGFLOAT_MIN;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    WEAKSELF
    switch (section) {
        case PostDetailSectionType_imgText:{

            PostDetailHeaderView *sectionHeader = [[NSBundle mainBundle] loadNibNamed:@"PostDetailHeaderView" owner:nil options:nil].firstObject;
            
            [sectionHeader fillWithModel:self.model];
            return sectionHeader;

        } break;
        case PostDetailSectionType_evaTap:{

            QADetailSectionHeaderView *sectionHeader = [[NSBundle mainBundle] loadNibNamed:@"QADetailSectionHeaderView" owner:nil options:nil].firstObject;
            
            sectionHeader.sectionTitleLab.text = [NSString stringWithFormat:@"全部评论(%ld)",(long)self.total];
            return sectionHeader;
            
        } break;
        default:{
            
            CommonEvaluateHeaderView *sectionHeader = [[NSBundle mainBundle] loadNibNamed:@"CommonEvaluateHeaderView" owner:nil options:nil].firstObject;
            
            CommunityEvaModel *headModel = self.dataArray[section - PostDetailSectionType_moreEva];
            [sectionHeader fillWithModel:headModel];
            
            sectionHeader.CommonEvaluateHeaderViewBlock = ^(CommunityActionType type) {
              
                weakSelf.aimModel = headModel;
                switch (type) {
                    case CommunityActionType_Thumb:{
                        
                        [weakSelf request_postThumbWithType:DetailreplyType_user WithModel:headModel];
                    }break;
                        
                    default:
                        break;
                }
            };
            
            [sectionHeader addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
               
                [weakSelf callSectionTFWithIndex:section - PostDetailSectionType_moreEva];
            }];
            
            return sectionHeader;

        } break;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {

    WEAKSELF
    switch (section) {
        case PostDetailSectionType_imgText:{

            UIView *footer = [[UIView alloc] init];
            footer.backgroundColor = [UIColor whiteColor];
            return footer;
            
        } break;
        case PostDetailSectionType_evaTap:{

            //无评论的无结果页放这里
            CommonNoEvaView  *sectionHeader = [[NSBundle mainBundle] loadNibNamed:@"CommonNoEvaView" owner:nil options:nil].firstObject;
            
            [sectionHeader addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
               
                weakSelf.bottomView.contentTF.placeholder = @"说说您的见解...";
                weakSelf.bottomView.contentTF.tag = DetailreplyType_post;
                [weakSelf.bottomView.contentTF becomeFirstResponder];
            }];
            
            return sectionHeader;

        } break;
        default:{
            
            CommonEvaluateFoldFooterView *sectionHeader = [[NSBundle mainBundle] loadNibNamed:@"CommonEvaluateFoldFooterView" owner:nil options:nil].firstObject;
            
            if (self.dataArray[section - PostDetailSectionType_moreEva].isFold) {
                sectionHeader.mainTitleLab.text = [NSString stringWithFormat:@"展开%lu条回复",(unsigned long)self.dataArray[section - PostDetailSectionType_moreEva].sysPostChildSideList.count];
                [sectionHeader.mainIcon setImage:[UIImage imageNamed:@"down_blue"]];
            } else {
                sectionHeader.mainTitleLab.text = @"收起";
                [sectionHeader.mainIcon setImage:[UIImage imageNamed:@"up_blue"]];
            }
            
            [sectionHeader addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
               
                self.dataArray[section - PostDetailSectionType_moreEva].isFold = !self.dataArray[section - PostDetailSectionType_moreEva].isFold;
                [self.tableview reloadData];
            }];
            
            return sectionHeader;

        } break;
    }
    return [UIView new];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    WEAKSELF
    switch (indexPath.section) {
        case PostDetailSectionType_imgText:{

            if (indexPath.row == 0) {
                PostDetailTextCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PostDetailTextCellID"];
                cell.selectionStyle =UITableViewCellSelectionStyleNone;
                cell.contentLab.attributedText = self.model.attrContent;
                return cell;
            } else {
                PostDetailImageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PostDetailImageCellID"];
                cell.selectionStyle =UITableViewCellSelectionStyleNone;
                                
                [cell.mainImageView sd_setImageWithURL:[NSURL URLWithString:self.model.sysMediaList[indexPath.row-1].url]  placeholderImage:[UIImage imageNamed:@"placeholder"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                    
                    if (image) {
                        weakSelf.model.sysMediaList[indexPath.row - 1].itemHeight = (image.size.height*(kScreenWidth-28)/image.size.width) + 10;
                    } else {
                        weakSelf.model.sysMediaList[indexPath.row - 1].itemHeight = TTScreenWidth - 20;
                    }                    
                    
                    [weakSelf.tableview reloadRow:indexPath.row inSection:indexPath.section withRowAnimation:UITableViewRowAnimationNone];
                }];
                
                return cell;
            }

            
        } break;
        case PostDetailSectionType_evaTap:{

            //无评论的无结果页放这里
            
        } break;
        default:{
            
            CommonEvaluateCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CommonEvaluateCellID"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            CommunityEvaModel *cellModel = self.dataArray[indexPath.section - PostDetailSectionType_moreEva].sysPostChildSideList[indexPath.row];
            [cell fillWithModel:cellModel];

            cell.CommonEvaluateCellBlock = ^(CommunityActionType type) {
              
                weakSelf.aimModel = cellModel;
                switch (type) {
                    case CommunityActionType_Thumb:{
                        [weakSelf request_postThumbWithType:DetailreplyType_replayUser WithModel:cellModel];
                    }break;
                        
                    default:
                        break;
                }
            };
            
            return cell;

        } break;
    }
    
    CommonEvaluateCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CommonEvaluateCellID"];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    return cell;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.section) {
        case PostDetailSectionType_imgText:{

        } break;
        case PostDetailSectionType_evaTap:{

        } break;
        default:{
            [self callCellTFWithIndexPath:indexPath];
        } break;
    }
}

- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.backgroundColor =  UIColorHex(0xf1f1f1);
        
        _tableview.showsHorizontalScrollIndicator = NO;
        _tableview.showsVerticalScrollIndicator = NO;
        
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.estimatedRowHeight = 0;
        
        [_tableview registerNib:[UINib nibWithNibName:@"PostDetailTextCell" bundle:nil] forCellReuseIdentifier:@"PostDetailTextCellID"];
        
        [_tableview registerNib:[UINib nibWithNibName:@"PostDetailImageCell" bundle:nil] forCellReuseIdentifier:@"PostDetailImageCellID"];
        
        [_tableview registerNib:[UINib nibWithNibName:@"CommonEvaluateCell" bundle:nil] forCellReuseIdentifier:@"CommonEvaluateCellID"];

        [self.view addSubview:_tableview];
        
        [_tableview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.right.mas_equalTo(0);
            make.bottom.mas_equalTo(self.bottomView.mas_top);
        }];
        
        WEAKSELF
        _tableview.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
            [weakSelf refreshParam];
            [weakSelf request_data];
        }];

        _tableview.mj_footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
            weakSelf.latestPageNum = weakSelf.pageNum;
            weakSelf.pageNum ++;
            [weakSelf request_data];
        }];
        
    }
    return _tableview;
}

- (CommonEvaluateBottomView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[NSBundle mainBundle] loadNibNamed:@"CommonEvaluateBottomView"owner:nil options:nil].firstObject;
        _bottomView.contentTF.delegate = self;
        
        [self.view addSubview:_bottomView];
        [_bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.mas_equalTo(0);
            make.height.mas_equalTo(Bottom_SafeHeight + 60);
        }];
    }
    return _bottomView;
}



- (void)request_postDetail {
        
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.pid forKey:@"pid"];
    [dic setValue:[TTUserModel sharedObject].userId forKey:@"replyUserId"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_PostDetail];
    
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
                
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSDictionary *resultDic = [data valueForKey:@"data"];
                
                if ([resultDic isKindOfClass:[NSDictionary class]]) {
                                        
                    if (weakSelf.pageNum == 1 && !weakSelf.model) {
                        
                        weakSelf.model = [CommonPostModel modelWithDictionary:resultDic];
                        weakSelf.model.textHeight = [Utilities getStringHeightWithText:weakSelf.model.content lineSpace:10 fontName:[UIFont systemFontOfSize:15] viewWidth:(TTScreenWidth - 28)] + 20;
                        
                        NSMutableParagraphStyle *style = [NSMutableParagraphStyle new];
                        style.lineSpacing = 10;
                        style.lineBreakMode = NSLineBreakByTruncatingTail;

                        NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:weakSelf.model.content];
                        [attrString addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, weakSelf.model.content.length)];
                        weakSelf.model.attrContent = attrString;
                                                
                        [weakSelf.actionBtn setTitle:weakSelf.model.themeTitle forState:UIControlStateNormal];
                        
                        CGFloat w = [Utilities getStringWidthWithString:weakSelf.model.themeTitle fontSize:18 andHeight:30];
                        self.actionBtn.imageEdgeInsets = UIEdgeInsetsMake(0, w + 15, 0, 0);
                        self.actionBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);

                        self.actionBtn.frame = CGRectMake(0, 0, w + 30, 44);

                        NSArray *sysMediaList = [resultDic valueForKey:@"sysMediaList"];
                        if ([sysMediaList isKindOfClass:[NSArray class]]) {
                            weakSelf.model.sysMediaList = @[].mutableCopy;
                            
                            for (id mediaDic in sysMediaList) {
                                CommonMediaModel *mediaModel = [[CommonMediaModel alloc] init];
                                mediaModel.itemHeight = 200;
                                if ([mediaDic isKindOfClass:[NSDictionary class]]) {
                                    NSDictionary *media = mediaDic;
                                    mediaModel = [CommonMediaModel modelWithDictionary:media];
                                }
                                if ([mediaDic isKindOfClass:[NSString class]]) {
                                    NSString *media = mediaDic;
                                    mediaModel.url = media;
                                }
                                [TT_OSSManager cacheSourceUrl:mediaModel.url];
                                [weakSelf.model.sysMediaList addObject:mediaModel];
                            }
                        }
                        weakSelf.model.sysPostChildList = @[].mutableCopy;
                        
                    }
                }
            } else {
                
                [TT_Alert alert:[data valueForKey:@"message"] doneAction:^{
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                }];
            }
        }
        dispatch_group_leave(self.group);
    } FailedBlock:^(NSError * _Nonnull error) {
        dispatch_group_leave(self.group);
    }];
}

- (void)request_evaList {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    NSMutableDictionary *t = @{}.mutableCopy;

    [dic setValue:@(self.pageNum) forKey:@"pageNum"];
    [dic setValue:@(self.pageSize) forKey:@"pageSize"];
    
    [t setValue:@"2" forKey:@"isDel"];
    [t setValue:self.pid forKey:@"pid"];
    [t setValue:[TTUserModel sharedObject].userId forKey:@"replyUserId"];
    [dic setValue:t forKey:@"t"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_PostChilds];
    
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
                
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSDictionary *resultDic = [data valueForKey:@"data"];
                
                if ([resultDic isKindOfClass:[NSDictionary class]]) {
                    NSArray *list = [resultDic valueForKey:@"list"];
                    weakSelf.total =[[resultDic valueForKey:@"total"] integerValue];
                    
                    if ([list isKindOfClass:[NSArray class]]) {
                        if (weakSelf.pageNum == 1) {
                            weakSelf.dataArray = @[].mutableCopy;
                        }
                        for (NSDictionary * evaDic in list) {
                            CommunityEvaModel *evaModel = [CommunityEvaModel modelWithDictionary:evaDic];
                            evaModel.isFold = YES;
                            evaModel.itemTotal = 0;
                            NSArray * sysPostChildSideList = [evaDic valueForKey:@"sysPostChildSideList"];
                            if ([sysPostChildSideList isKindOfClass:[NSArray class]]) {
                                evaModel.sysPostChildSideList = @[].mutableCopy;
                                for (NSDictionary *childEva in sysPostChildSideList) {
                                    CommunityEvaModel *childEvaModel = [CommunityEvaModel modelWithDictionary:childEva];
                                    childEvaModel.level = @"3";

                                    //正常的二级添加
                                    evaModel.itemTotal++;
                                    [evaModel.sysPostChildSideList addObject:childEvaModel];
                                    
                                    NSArray * threeList = [childEva valueForKey:@"sysPostChildSideNextList"];
                                    if ([threeList isKindOfClass:[NSArray class]]) {
                                        for (NSDictionary *threeDic in threeList) {
                                            CommunityEvaModel *threeEvaModel = [CommunityEvaModel modelWithDictionary:threeDic];
                                            
                                            threeEvaModel.content = [NSString stringWithFormat:@"回复 %@:%@",threeEvaModel.userNickName,threeEvaModel.content];
                                            threeEvaModel.level = @"4";
                                            //把三级加到二级里面
                                            evaModel.itemTotal++;
                                            [evaModel.sysPostChildSideList addObject:threeEvaModel];
                                        }
                                    }
                                }
                            }
                            [weakSelf.dataArray addObject:evaModel];
                        }
                        
                        if (list.count == 0) {
                            weakSelf.pageNum =weakSelf.latestPageNum;
                        }
                    }
                }
            }
        }
        dispatch_group_leave(self.group);
    } FailedBlock:^(NSError * _Nonnull error) {
        
        dispatch_group_leave(self.group);
    }];
}

//

- (void)request_postEvaWithType:(DetailreplyType)type {
        
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.bottomView.contentTF.text forKey:@"content"];
    
    switch (type) {
        case DetailreplyType_post:{
            
            [dic setValue:self.pid forKey:@"baseId"];
            [dic setValue:@"2" forKey:@"level"];
            [dic setValue:self.model.source forKey:@"source"];
            [dic setValue:self.model.userId forKey:@"userId"];
        } break;
        case DetailreplyType_user:{
            
            //回复评论    level 3          cpId
            [dic setValue:self.aimModel.cpId forKey:@"baseId"];
            [dic setValue:@"3" forKey:@"level"];

            [dic setValue:self.aimModel.source forKey:@"source"];
            [dic setValue:self.aimModel.userId forKey:@"userId"];
        } break;
        case DetailreplyType_replayUser:{

            //回复别人对我的回复   level 4      cspid
            [dic setValue:self.aimModel.cspId forKey:@"baseId"];
            [dic setValue:self.aimModel.cspnId forKey:@"cspnId"];

            [dic setValue:@"4" forKey:@"level"];

            [dic setValue:self.aimModel.replySource forKey:@"source"];
            [dic setValue:self.aimModel.replyUserId forKey:@"userId"];
        } break;
        default:
            break;
    }
    
    //操作类型（1：评论，2：点赞，3：删除，4：下架，5：取消点赞）必传
    [dic setValue:@"1" forKey:@"mold"];

    //类型（1：谈婚，2：论嫁，3：问答）必传
    [dic setValue:@"1" forKey:@"type"];
    //层级（1,2,3）必传
    [dic setValue:@"2" forKey:@"replySource"];
    [dic setValue:[TTUserModel sharedObject].userId forKey:@"replyUserId"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_CommonEva];
    
    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在发布评论"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {

        [[TTNoResultManager shareManager] hideNoResultWithView:weakSelf.tableview];
        
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                weakSelf.bottomView.contentTF.text = @"";
                [weakSelf.view endEditing:YES];
                
                [weakSelf refreshParam];
                [weakSelf request_data];
            } else {
                
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
    }];
}


- (void)request_postThumbWithType:(DetailreplyType)type WithModel:(id)aimModel {
        
    NSMutableDictionary *dic = @{}.mutableCopy;
        
    NSString *isZan;
    switch (type) {
        case DetailreplyType_post:{
            CommonPostModel *model = aimModel;
            //点赞帖子
            [dic setValue:model.pid forKey:@"baseId"];
            [dic setValue:@"1" forKey:@"level"];
            [dic setValue:model.source forKey:@"source"];
            [dic setValue:model.userId forKey:@"userId"];
            isZan = model.isZan;
        } break;
        case DetailreplyType_user:{
            CommunityEvaModel *model = aimModel;
            //点赞评论          cpId
            [dic setValue:model.cpId forKey:@"baseId"];
            [dic setValue:@"2" forKey:@"level"];
            [dic setValue:model.source forKey:@"source"];
            [dic setValue:model.userId forKey:@"userId"];
            isZan = model.isZan;
        } break;
        case DetailreplyType_replayUser:{

            //点咋别人对我的回复      cspid
            CommunityEvaModel *model = aimModel;
            if ([model.level isEqualToString:@"3"]) {
                [dic setValue:model.cspId forKey:@"baseId"];
            }
            if ([model.level isEqualToString:@"4"]) {
                [dic setValue:model.cspnId forKey:@"baseId"];
            }
            [dic setValue:model.level forKey:@"level"];
            [dic setValue:model.replySource forKey:@"source"];
            [dic setValue:model.replyUserId forKey:@"userId"];
            isZan = model.isZan;

        } break;
        default:
            break;
    }
    
    //操作类型（1：评论，2：点赞，3：删除，4：下架，5：取消点赞）必传
    if (isZan.length > 0) {
        [dic setValue:@"5" forKey:@"mold"];
        [dic setValue:isZan forKey:@"otherId"];
    } else {
        [dic setValue:@"2" forKey:@"mold"];
    }

    [dic setValue:@"1" forKey:@"type"];//类型（1：谈婚，2：论嫁，3：问答）必传
    [dic setValue:@"2" forKey:@"replySource"];//层级（1,2,3）必传
    [dic setValue:[TTUserModel sharedObject].userId forKey:@"replyUserId"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_CommonEva];
    
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {

        [[TTNoResultManager shareManager] hideNoResultWithView:weakSelf.tableview];
        
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                
                NSString *Zan = [data valueForKey:@"data"];

                switch (type) {
                    case DetailreplyType_post:{
                        
                        CommonPostModel *model = aimModel;
                        if ([Zan isKindOfClass:[NSString class]]) {
                            model.isZan = Zan;
                            if (Zan.length > 0) {
                                model.likes++;
                            } else {
                                model.likes--;
                            }
                            [weakSelf.bottomView fillWithModel:weakSelf.model];;
                        }

                    } break;
                    case DetailreplyType_user:{
                        
                        CommunityEvaModel *model = aimModel;
                        if ([Zan isKindOfClass:[NSString class]]) {
                            model.isZan = Zan;
                            if (Zan.length > 0) {
                                model.likes++;
                            } else {
                                model.likes--;
                            }
                            [weakSelf.tableview reloadData];
                        }

                    } break;
                    case DetailreplyType_replayUser:{

                        CommunityEvaModel *model = aimModel;
                        if ([Zan isKindOfClass:[NSString class]]) {
                            model.isZan = Zan;
                            if (Zan.length > 0) {
                                model.likes++;
                            } else {
                                model.likes--;
                            }
                            [weakSelf.tableview reloadData];
                        }
                        
                    } break;
                    default:
                        break;
                }
                
            } else {
                
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {

    }];
}


@end
